#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import logging
import os
import sys

from pathlib import Path


logging.basicConfig(stream=sys.stderr, level=logging.INFO)
LOG = logging.getLogger(__name__)


def get_installed_extensions(extensions_config):
    with open(extensions_config) as f:
        data = json.load(f)
    extensions = [extension.get('relativeLocation') for extension in data]
    return extensions

def rm_directory(directory):
    for root, dirs, files in os.walk(directory, topdown=False):
        for name in files:
            LOG.debug('Remove file: %s', os.path.join(root, name))
            os.remove(os.path.join(root, name))
        for name in dirs:
            LOG.debug('Remove directory: %s', os.path.join(root, name))
            os.rmdir(os.path.join(root, name))
    os.rmdir(directory)

def prune_unused_extensions():
    extensions = get_installed_extensions('extensions.json')

    current_dir = Path.cwd()
    unused_extensions = []
    for item in current_dir.iterdir():
        if item.is_dir() and item.name not in extensions:
            unused_extensions.append(item.name)
    for item in unused_extensions:
        try:
            rm_directory(item)
        except OSError as e:
            LOG.warning(e)
        except FileNotFoundError:
            continue


if __name__ == '__main__':
    prune_unused_extensions()
